package com.liusy.serachengine.mail;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;


public class resolveMail {
   private static Logger log = Logger.getLogger(resolveMail.class);

   public Map getInfo(String filepath, String rootPath, String attachPath, String virtualPath, int currentMaxId) {
      Map map = new HashMap();
      String logInfo = "";
      BufferedReader br=null;
      try {
         logInfo = "解析 " + filepath;
         writeLog(logInfo, 2);

         br = new BufferedReader(new FileReader(filepath));
         String lineContent = null;
         int lineCount = 0;

         //存header信息时用到的辅助参数
         boolean flag1 = false;
         int count1 = 0;
         Map head = new HashMap();
         StringBuffer originalHead = new StringBuffer();
         //存附件信息时用到的辅助参数
         boolean flag2 = false;
         int count2 = 0;
         int attachCount = 0;
         List attachments = new ArrayList();
         //存正文信息时用到的辅助参数
         boolean flag3 = false;
         int count3 = 0;
         StringBuffer content = new StringBuffer();
         while ((lineContent = br.readLine()) != null) {
            lineCount++;

            //过滤掉类似 index_d_a_0.html 这样的文件
            if (lineCount == 4) {
               if (lineContent.indexOf("Index</title>") != -1) {
                  logInfo = filepath + " 被过滤，原因：不是正确的html邮件。";
                  writeLog(logInfo, 1);
                  return null;
               }
            }
            //header信息
            if (lineContent.equals("						<div id=\"headerdata\">")) {
               flag1 = true;
            }
            if (flag1 && lineContent.equals("						</div>")) {
               flag1 = false;
               map.put("head", head);
               map.put("originalHead", originalHead.toString());
            }
            if (flag1) {
               count1++;
               if (count1 >= 4) { //开始记录header信息
                  originalHead.append(lineContent);
                  String headStr = lineContent;
                  if (lineContent.indexOf("<br />") != -1) headStr = lineContent.substring(0, lineContent.indexOf("<br />"));

                  String key = headStr.substring(0, headStr.indexOf(": "));
                  String value = headStr.substring(headStr.indexOf(": ") + 2).replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">");
                  if (key.equals("message-id")) {
                     String msgid = value;
                     //除重，并过滤掉类似 12h.html 这样的文件（与12.html的message-id相同）
                  }
                  if (key.equals("date")) {
                     Date date = null;
                     date = parseDate(value, "E, dd MMM yyyy HH:mm:ss Z");
                     if (date == null) date = parseDate(value, "dd MMM yyyy HH:mm:ss Z");
                     if (date == null) date = parseDate(value + "00", "dd MMM yyyy HH:mm:ss Z");
                     if (date == null) {
                        logInfo = filepath + ":dateformat(" + value + ") error.";
                        writeLog(logInfo, 0);
                     }
                     head.put(key, date);
                  }
                  else {
                     head.put(key, value);
                  }

               }
            }

            //附件
            if (lineContent.equals("						<div class=\"attachment\">")) {
               flag2 = true;
            }
            if (flag2 && lineContent.equals("					</div>")) {
               flag2 = false;
               map.put("attachments", attachments);
            }
            if (flag2) {
               count2++;
               if (count2 >= 2) { //开始记录附件信息
                  if (lineContent.indexOf("<a href") == -1) {
                     //当有多个附件时，存在这样的行：					</div><div class="attachment">
                     //应将该行忽略
                     continue;
                  }

                  String path = lineContent.substring(lineContent.indexOf("href=\"") + 6, lineContent.indexOf("\" onclick"));
                  String str = lineContent.substring(lineContent.indexOf(">") + 1, lineContent.indexOf(")</a>"));
                  int pos = str.lastIndexOf("(");
                  String name = str.substring(0, pos);
                  String size = str.substring(pos + 1);
                  int current = currentMaxId + attachCount;

                  File fileFrom = new File(rootPath + "\\" + path);
                  String attachname = virtualPath + "\\" + current + "_" + fileFrom.getName();
                  File fileTo = new File(attachPath + "\\" + current + "_" + fileFrom.getName());
                  if (!copyFile(fileFrom, fileTo)) {
                     logInfo = filepath + "的附件" + path + "复制出错！";
                     writeLog(logInfo, 0);
                  }
                  else {

                     Map attachment = new HashMap();
                     attachment.put("id", current + "");
                     attachment.put("filename", attachname);
                     attachment.put("attchname", name);
                     attachment.put("attchsize", fileFrom.length() + " bytes");

                     attachCount++;

                     attachments.add(attachment);
                  }

               }
            }

            //正文
            if (lineContent.equals("					<td class=\"body\" colspan=2>")) {
               flag3 = true;
            }
            if (flag3 && lineContent.equals("					</td>")) {
               flag3 = false;
               map.put("content", content.toString());
            }
            if (flag3) {
               count3++;
               if (count3 >= 2) { //开始记录正文信息
                  content.append(lineContent);
               }
            }
         }
         logInfo = filepath + ":sucess.";
         writeLog(logInfo, 2);
      }
      catch (FileNotFoundException e) {
         logInfo = filepath + ":error.";
         writeLog(logInfo, 0);
         e.printStackTrace();
      }
      catch (IOException e) {
         logInfo = filepath + ":error.";
         writeLog(logInfo, 0);
         e.printStackTrace();
      }
      catch (Exception e) {
         logInfo = filepath + ":error.";
         writeLog(logInfo, 0);
         e.printStackTrace();
      }
      finally{
    	try {
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
      }
      return map;

   }

   private Date parseDate(String str, String partten) {
      try {
         SimpleDateFormat sf = new SimpleDateFormat(partten, Locale.ENGLISH);
         return sf.parse(str);
      }
      catch (ParseException pe) {
         return null;
      }
   }

   private boolean copyFile(File fileFrom, File fileTo) {
      try {
         FileInputStream in = new FileInputStream(fileFrom);
         FileOutputStream out = new FileOutputStream(fileTo);
         byte[] bt = new byte[1024];
         int c;
         while ((c = in.read(bt)) > 0) {
            out.write(bt, 0, c);
         }
         out.close();
         in.close();
      }
      catch (Exception e) {
         e.printStackTrace();
         return false;
      }
      return true;
   }

   /**
    * 记日志，包括log4j和显示在界面的日志信息
    * 
    * @param logInfo
    * @param flag
    *           0：错误信息，1：提示信息，2:正确信息
    */

   private void writeLog(final String logInfo, int flag) {
      log.info(logInfo);
   }
}
